import type { App } from "vue";

import { createRouter, createWebHashHistory } from "vue-router";

import { BasicRoutes } from "@/routers/modules";

import type { Router } from "vue-router";

class RouterUtils {
  constructor(router: Router) {
    this.router = router;
  }

  // 判断路径是否存在
  exist() {
    console.log(this.router);
    return true;
  }

  // 判断用户是否有权限
  permission() {
    return true;
  }

  // 判断用户是否登陆
  userLogin() {
    return true;
  }
}

// 总路由
export const router = createRouter({
  history: createWebHashHistory(),
  routes: BasicRoutes,
  strict: true,
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

// 路由守卫(前置)
router.beforeEach((to, from, next) => {
  const toPath = to.path;
  const routerUtils = new RouterUtils(router);
  const exist = routerUtils.exist(toPath);

  // 判断路由是否存在， 不存在重定向到404
  if (exist) {
    // 判断用户是否登陆
    const userLogin = routerUtils.userLogin();
    if (!userLogin && to.name !== "Login") {
      next({ name: "Login" });
    } else {
      if (userLogin && to.name === "Login") {
        next({ name: "Admin" });
      } else {
        next();
      }
    }
  } else {
    next({ name: "notFound" });
  }
});

// 路由守卫(后置)

// 注册路由
export function setupRouter(app: App<Element>) {
  app.use(router);
}
